<template>
  <el-container>
    <el-header>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="图片" name="first"></el-tab-pane>
        <el-tab-pane label="视频" name="second"></el-tab-pane>
      </el-tabs>
    </el-header>
    <el-container>
      <el-aside width="200px">
        <div :class="['c-menu',channelName==''?'c-current':'']" @click="getALLChannelId()">
          <span>
            <i class="el-icon-folder"></i>
             全部
          </span>
        </div>
        <div v-for="item in channelList" :class="['c-menu',item.channelName==channelName?'c-current':'']"
             @click="getChannelId(item)">
          <span>
            <i class="el-icon-folder"></i>
             {{ item.channelName }}
          </span>
        </div>
      </el-aside>
      <el-main>
        <div class="cms-list-header c-clearfix">
          <div class="c-fl pt5">
            <el-checkbox v-model="checkAll" @change="setCheckAll()"></el-checkbox>
            <span>{{channelName==""?"全部":channelName}}</span>
          </div>
          <div class="content-flex-right c-fr">
            <cms-input label="附件名称" v-model="params.fileRemark"></cms-input>
            <el-button @click="goQuery()">查询</el-button>
            <el-button type="danger" icon="el-icon-delete" circle
                       @click="deleteBatch($api.attachmentDelete)"></el-button>
          </div>
        </div>
        <div class="c-img-list c-clearfix">
          <div v-for="(item,index) in tableData" :class="['c-fl', 'c-img-item', item.checked?'c-checked':'']">
            <div class="c-border" @mouseenter="show(index)" @mouseleave="hide()">
              <!--图片-->
              <div v-if="item.fileType=='picture'" @click="goPreviewImg(item)">
                <img :src="item.filePath" :alt="item.fileRemark"
                     :title="'【'+(item.channelName==''?'全部':item.channelName)+'】'+item.fileRemark"
                     style="cursor: pointer;" @error="defImg()" />
              </div>
              <!--OSS视频-->
              <div v-else-if="item.fileType=='video' && item.uploadWay==1"
                   :title="'【'+(item.channelName==''?'全部':item.channelName)+'】'+item.fileRemark">
                <video :src="item.filePath" controls="controls" :autoplay="false" height="134px" width="134px"></video>
              </div>
              <!--点播视频-->
              <div v-else-if="item.fileType=='video' && item.uploadWay==2"
                   :title="'【'+(item.channelName==''?'全部':item.channelName)+'】'+item.fileRemark"
                   @click="goPreview(item.videoId)">
                <img src="../../../../static/images/add-video.png" height="134" width="134" style="cursor: pointer;"
                     title="点击预览"/>
              </div>
              <div v-if="bianji&&index==current" class="bianji" @click="showEditDialog(item)" title="点击编辑说明"><i class="bianji-icon"></i></div>
              <div v-if="bianji&&index==current" class="copy" @click="goCopy(item)" title="复制图片链接"><i class="copy-icon"></i></div>
            </div>
            <div class="c-fl c-choose">
              <el-checkbox v-model="item.checked" @change="attachmentCheck()"></el-checkbox>
            </div>
            <span class="ellipsis">{{item.fileRemark}}</span>
          </div>
          <div class="c-fl c-img-item">
            <img src="../../../../static/images/add-img.png" height="135" width="135" style="cursor: pointer;"
                 title="点击添加" @click="showAddAttachment()"/></div>
        </div>
        <div class="cms-list-footer">
          <div class="cms-left">
          </div>
          <cms-pagination :total="total" :limit="params.pageSize" @change="getPages"></cms-pagination>
        </div>
      </el-main>
    </el-container>
    <span class="message" v-show="isShow">{{word}}</span>
    <el-dialog :visible.sync="isShowVideo" v-if="isShowVideo" size="small" width="540px" height="300px">
      <aliPlayer :videoId="videoId" :playAuth="playAuth" v-if="isShowVideo"></aliPlayer>
    </el-dialog>
    <el-dialog :visible.sync="isShowImageDialog" v-if="isShowImageDialog">
      <img :src="attachmentImgpath|imgPathFilter"
           style="max-width: 100%;max-height: 100%;display: block; margin: 0 auto;"/>
    </el-dialog>
    <el-dialog :visible.sync="isShowDialog" v-if="isShowDialog" title="上传附件" width="40%">
      <el-form ref="form" :model="uploadInfo" :rules="checkRule">
        <el-form-item label="选择频道" style="margin-left: 20px">
          <el-select @change="selectChange" v-model="uploadInfo.channelId" clearable placeholder="请选择">
            <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                       :value="item.channelId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传类型" prop="fileType" style="margin-left: 10px">
          <el-select v-model="uploadInfo.fileType">
            <el-option label="图片" value="picture"></el-option>
            <el-option label="视频" value="video"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="视频上传" v-if="uploadInfo.fileType=='video'" style="margin-left: 20px">
          <el-select v-model="uploadInfo.uploadWay">
            <el-option label="oss上传" value="1"></el-option>
            <el-option label="点播上传" value="2"></el-option>
          </el-select>
        </el-form-item>
        <div style="margin-left: 15px;margin-bottom: 15px;">
          <span style="vertical-align: top;">附件名称：</span>
          <el-input class="cms-width" style="width: 300px;" placeholder="图片说明"
                    v-model="uploadInfo.fileRemark" type="textarea"></el-input>
        </div>

        <el-form-item v-if="uploadInfo.fileType=='picture'">
          <cms-batch-pictrues :action="action" @change="getAttachment" @remove="removeAttachment"
                              uploadPath="images"></cms-batch-pictrues>
        </el-form-item>

        <el-form-item v-if="uploadInfo.uploadWay==1 && uploadInfo.fileType=='video'">
          <cms-batch-multiple-upload :action="action" @change="getAttachment" :limit="1" @remove="removeAttachment"
                                     uploadPath="video"></cms-batch-multiple-upload>
        </el-form-item>

        <el-form-item v-if="uploadInfo.uploadWay==2 && uploadInfo.fileType=='video'">
          <ali-video-only-upload @change="getAttachment" @remove="removeAttachment"
                                 uploadPath="video"></ali-video-only-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
       <el-button type="primary" @click="add()">保 存</el-button></span>
    </el-dialog>
    <el-dialog :visible.sync="isShowEditDialog" v-if="isShowEditDialog" title="附件名称修改">
      <el-form ref="form" :model="dataInfo" class="cms-form" label-width="162px">
        <el-form-item label="附件Id" class="flex-100" prop="attachmentId">
          <el-input v-model="dataInfo.attachmentId" class="cms-width" :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="附件类型" class="flex-100" prop="fileType">
          <el-select v-model="dataInfo.fileType" :disabled="true">
            <el-option label="图片" value="picture"></el-option>
            <el-option label="视频" value="video"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择频道">
          <el-select @change="selectChange" v-model="dataInfo.channelId" clearable placeholder="请选择">
            <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
                       :value="item.channelId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件名称" class="flex-100" prop="fileRemark">
          <el-input v-model="dataInfo.fileRemark" placeholder="图片说明" class="cms-width" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="form-footer">
        <el-button type="primary" @click="update()" v-perms="'/keyword/update'">修改
        </el-button>
      </div>
    </el-dialog>
  </el-container>
</template>
<script>
  import listMixins from '@/mixins/list'
  import formMixns from "@/mixins/form";
  import axios from "axios";
  import {setBaseUrl} from '@/config.js'
  import va from "@/rules";

  export default {
    mixins: [listMixins, formMixns],

    data() {
      let required = va.required("此项必填");
      return {
        globalUrl: setBaseUrl(),
        fileTypes: [],
        names: '',
        action: this.$api.attachmentBatchUpload,
        params: {
          channelId: '',
          fileType: 'picture',
          fileRemark: '',
          pageNo: 1,
          pageSize: 30
        },
        channelList: [],
        checkAll: false,
        isShowDialog: false,
        isShowVideo: false,
        isShowEditDialog: false,
        isShowImageDialog: false,
        uploadInfo: {
          channelId: '',
          fileType: '',
          fileRemark: ''
        },
        checkRule: {
          fileType: [required],
        },
        attachmentList: [],
        videoId: '',
        playAuth: '',
        isShow: false,
        word: 'success',
        activeName: 'first',
        channelName: '',
        bianji: false,
        current: 0,
        attachmentImgpath: '',
        dialogLoading: false,
        dataInfo: {},
        defaultImg:'../../../../static/images/default.png',  // 图片加载默认图
      }
    },
    methods: {
      getALLChannelId() {
        // 全部
        this.channelName = ""
        this.params.channelId = "";
        this.params.fileRemark = '';
        this.params.pageNo = 1;
        this.params.pageSize = 30;
        this.getAttachmentTableData();
      },
      getChannelId(channel) {
        // 选择频道
        //console.log(channel)
        this.channelName = channel.channelName
        this.params.channelId = channel.channelId;
        this.params.fileRemark = '';
        this.params.pageNo = 1;
        this.params.pageSize = 30;
        this.getAttachmentTableData();
      },
      handleClick(tab, event) {
        //console.log(tab.name);
        if (tab.name == 'first') {
          this.params.fileType = 'picture';
        }
        if (tab.name == 'second') {
          this.params.fileType = 'video';
        }
        this.channelName = ""
        this.params.channelId = "";
        this.params.fileRemark = "";
        this.params.pageNo = 1;
        this.params.pageSize = 30;
        this.goQuery();
        this.initCheckData(false);
        this.checkAll = false;
      },
      attachmentCheck() {
        this.checkAll = true
        for (let i in this.tableData) {
          let attachment = this.tableData[i];
          let checked = attachment.checked;
          if (!checked) {
            this.checkAll = false;
            this.choose = !this.choose
          }
        }
      },
      showAddAttachment() {
        if (this.params.channelId != "") {
          this.uploadInfo.channelId = this.params.channelId;
        }
        if (this.params.fileType == "picture") {
          this.uploadInfo.fileType = "picture";
        } else if (this.params.fileType == "video") {
          this.uploadInfo.fileType = "video";
        }
        this.isShowDialog = true;
      },
      showUpload() {
        this.isShowDialog = true;
        this.dialogTitle = '上传附件';
      },
      removeAttachment(index) {
        this.attachmentList.splice(index, 1);
      },
      uploadChange() {
        this.getTableData(this.params);
      },
      selectChange(val) {
        this.uploadInfo.channelId = val;
      },
      getAttachment(attachmentList) {
        if (!this.$myUtils.isNull(attachmentList)) {
          this.attachmentList = this.attachmentList.concat(attachmentList);
        }
      },
      deleteBatch(url) { //删除
        let ids = [];
        for (let i in this.tableData) {
          let attachment = this.tableData[i];
          let checked = attachment.checked;
          let id = attachment.id;
          if (checked) {
            ids.push(id);
          }
        }
        if (ids.length == 0) {
          this.errorMessage("请选择删除附件");
          return;
        }
        ids = ids.join(",");
        this.$confirm('是否确定删除？', '警告', {type: "error"}).then(mes => {
          this.$http.post(url, {ids: ids}).then(res => {
            console.log(res);
            if (res.code == "200") {
              this.successMessage('删除成功');
              this.getAttachmentTableData();
            }
          });
        }).catch(error => {
          console.log(error);
        });
      },
      add() {
        if (this.attachmentList.length <= 0) {
          this.errorMessage("请上传附件");
          return;
        }
        for (let i in this.attachmentList) {
          let attachment = this.attachmentList[i];
          attachment['fileRemark'] = this.uploadInfo.fileRemark
        }
        this.uploadInfo.attachmentData = JSON.stringify(this.attachmentList);
        let form = this.$refs['form'];
        console.log(form)
        form.validate((valid) => {//验证方法
          console.log('表单校验结果' + valid);
          if (valid) {
            this.loading = true;
            axios.post(this.$api.attachmentBatchSave, this.uploadInfo).then(res => {
              if (res.code == "200") {
                this.successMessage('添加成功');
                setTimeout(() => {
                  this.isShowDialog = false;
                  let fileType = this.uploadInfo.fileType;
                  this.params.fileType = fileType;
                  this.initTableData(this.$api.attachmentPageList, this.params);
                  this.attachmentList = [];
                  this.uploadInfo = {}
                }, 1000);
              }
              this.loading = false;
            }).catch(error => {
              console.log(error)
              this.loading = false;
            })
          } else {
            return false
          }
        })
      },
      getChannelList() {
        axios.all([
          axios.post(this.$api.getOneLevelChannelList, {}),
        ]).then(
          axios.spread((channelRes) => {
            this.channelList = channelRes.body;
          })
        )
      },
      getPlayAuthInfo(videoId) {
        let url = this.$api.getPlayAuthInfo;
        axios.post(url, {videoId: videoId}).then(res => {
          console.log(res)
          if (res.code == "200") {
            let playAuth = res.body.playAuth;
            if (this.$myUtils.isNull(playAuth)) {
              this.errorMessage("预览失败,获取鉴权信息失败");
            } else {
              this.playAuth = playAuth;
              this.isShowVideo = true;
            }
          }
        });
      },
      goPreviewImg(attachment) {
        this.isShowImageDialog = true;
        this.attachmentImgpath = attachment.filePath;
      },
      goPreview(videoId) {
        if (this.$myUtils.isNull(videoId)) {
          this.errorMessage("预览失败缺少videoId");
        } else {
          this.videoId = videoId;
          this.getPlayAuthInfo(videoId);
        }
      },
      goCopy(attachment) {
        console.log(attachment); //每一行的数据
        let filePath = attachment.filePath;
        let oInput = document.createElement('input');
        oInput.value = filePath; //赋值
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象
        document.execCommand("Copy"); // 执行浏览器复制命令
        oInput.className = 'oInput';
        oInput.style.display = 'none';
        this.successMessage('复制成功');
      },
      setCheckAll() {
        this.initCheckData(this.checkAll);
      },
      initCheckData(checked) {
        for (let i in this.tableData) {
          let attachment = this.tableData[i];
          attachment.checked = checked;
        }
      },
      getAttachmentTableData() {
        this.initTableData(this.$api.attachmentPageList, this.params);
        this.initCheckData(false);
      },
      show(index) {
        this.bianji = true;
        this.current = index;
      },
      hide() {
        this.bianji = false;
        this.current = null;
      },
      showEditDialog(attachment) {
        this.isShowEditDialog = true;
        this.getDataInfo(attachment);
      },
      getDataInfo(attachment) {
        axios.post(this.$api.attachmentGet, {attachmentId: attachment.id}).then(res => {
          console.log(res)
          this.loading = false;
          this.$refs["form"].resetFields();
          this.dataInfo = res.body; //将用户数据复制给dataInfo
        })
        this.loading = false;
      },
      update() {
        this.loading = true;
        axios.post(this.$api.attachmentUpdate, this.dataInfo).then(res => {
          this.loading = false;
          if (res.code == "200") {
            this.successMessage('修改成功');
            this.params.fileType = this.dataInfo.fileType;
            this.getAttachmentTableData();
            this.isShowEditDialog = false;
          }
        }).catch(error => {
          this.loading = false;
        })
      },
      defImg(){
        // 图片加载不出来显示默认图
        let img = event.srcElement;
        img.src = this.defaultImg;
        img.onerror = null; //防止闪图
      }
    },
    created() {
      this.getChannelList();
      this.getAttachmentTableData();
    }
  };
</script>

<style scoped>
  .cms-list-header span {
    text-transform: lowercase;
  }

  .el-table__row .cell .icon-wenjianjiabiheicon,
  .el-table__row .cell .icon-file {
    color: #ffc822;
  }

  .upload-demo {
    margin-left: 6px
  }

  .icon-wenjianjiabiheicon,
  .icon-shijian,
  .icon-file {
    font-size: 20px;
    position: relative;
    top: 3px;
  }

  .icon-unie62e {
    color: #00aeff;
  }

  .uploadDiv,
  .uploading {
    display: inline-block;
  }

  .el-container {
    padding: 10px 20px 0 20px;
  }

  .el-aside {
    background: #f5f5f5;
    padding: 10px;
    min-height: 100vh;
  }

  .c-menu {
    width: 100%;
    height: 30px;
    margin-bottom: 10px;
    padding: 0 15px;
    cursor: pointer;
    line-height: 30px;
  }

  .c-menu span {
    color: #444;
  }

  .c-menu .el-icon-folder {
    font-size: 18px;
    color: #EEA12E;
    margin-right: 5px;
  }

  .c-clearfix:after {
    content: "";
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
  }

  .c-clearfix {
    zoom: 1;
  }

  .pt5 {
    padding-top: 5px;
  }

  .c-fl {
    float: left;
  }

  .c-fr {
    float: right;
  }

  .cms-list-header {
    padding: 0 0 15px 0;
    border-bottom: 1px solid #e7ecf3;
  }

  .el-button--default {
    background: #EEA12E;
    color: #fff;
    border-color: #EEA12E;
  }

  .el-button.is-circle {
    border: none;
    background: none;
    padding: 0;
    min-width: 20px;
    color: #F56C6C;
    font-size: 20px;
    vertical-align: middle;
    margin-left: 20px;
  }

  .c-img-list {
    padding-top: 15px;
  }

  .c-img-item {
    width: 135px;
    margin: 0px 15px 15px 0px;
  }

  .c-border {
    width: 135px;
    height: 135px;
    display: block;
    border: 1px solid #eee;
    position: relative;
  }

  .c-img-item img {
    width: 134px;
    height: 134px;
    border: none;
    object-fit: contain;
  }

  .ellipsis {
    display: -webkit-box;
    overflow: hidden;
    white-space: normal !important;
    text-overflow: ellipsis;
    word-wrap: break-word;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }

  .c-img-item span {
    line-height: 30px;
    font-size: 14px;
    padding-left: 5px;
  }

  .el-main {
    padding-top: 0;
  }

  .el-header {
    height: 50px !important;
  }

  .c-current {
    background: #fff;
  }

  .bianji {
    position: absolute;
    width: 24px;
    height: 24px;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, .5);
  }

  .bianji-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin: 5px;
    background: url("/static/images/bianji.png") no-repeat;
    background-size: 14px;
    cursor: pointer;
  }

  .c-checked .c-border {
    box-shadow: 0px 0px 5px 2px rgba(226, 75, 1, 0.5);
  }

  .c-choose {
    margin-top: 5px;
  }
  .copy {
    position: absolute;
    width: 24px;
    height: 24px;
    top: 0;
    right: 0;
    background: rgba(0, 0, 0, .5);
  }

  .copy-icon {
    display: inline-block;
    width: 16px;
    height: 16px;
    margin: 5px;
    background: url("/static/images/copy.png") no-repeat;
    background-size: 14px;
    cursor: pointer;
  }

</style>

